#include <func.h>

int main(int argc,char* argv[])
{
    ARGS_CHECK(argc,3);
    int sfd;
    sfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sfd,-1,"socket");
    printf("sfd=%d\n",sfd);
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));
    ser_addr.sin_family=AF_INET;
    ser_addr.sin_addr.s_addr=inet_addr(argv[1]);
    ser_addr.sin_port=htons(atoi(argv[2]));
    int ret=bind(sfd,(struct sockaddr*)&ser_addr,sizeof(ser_addr));
    ERROR_CHECK(ret,-1,"bind");
    ret=listen(sfd,10);
    ERROR_CHECK(ret,-1,"listen");
    int new_fd;
    struct sockaddr_in cli_addr;
    bzero(&cli_addr,sizeof(cli_addr));
    socklen_t addr_len=sizeof(cli_addr);
    new_fd=accept(sfd,(struct sockaddr*)&cli_addr,&addr_len);
    ERROR_CHECK(new_fd,-1,"accept");
    printf("i accept you,ip is %s,port is %d\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
    char buf[128]={0};
    fd_set reset;
    while(1)
    {
        FD_ZERO(&reset);
        FD_SET(STDIN_FILENO,&reset);
        FD_SET(new_fd,&reset);
        ret=select(new_fd+1,&reset,NULL,NULL,NULL);
        if(FD_ISSET(STDIN_FILENO,&reset))
        {
            bzero(buf,sizeof(buf));
            ret=read(STDIN_FILENO,buf,sizeof(buf));
            if(!ret)
            {
                printf("i want to go\n");
                break;
            }
            send(new_fd,buf,strlen(buf)-1,0);
        }
        if(FD_ISSET(new_fd,&reset))
        {
            bzero(buf,sizeof(buf));
            ret=recv(new_fd,buf,sizeof(buf),0);
            if(!ret)
            {
                printf("byebye\n");
                break;
            }
            printf("%s\n",buf);
        }
    }
    close(new_fd);
    close(sfd);
    return 0;
} 